import {Component, OnInit} from '@angular/core';
import {AbstractControl, FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ActivatedRoute, Router} from '@angular/router';
import {LoginService} from './login.service';
import {SysUser} from '../module/system-management/sys-user/sys-user.type';
import {Md5} from 'ts-md5';
import {environment} from '../../environments/environment';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

    envNickname = environment.nickname;
    envVersion = environment.version;
    showError = false;
    systemErrorMessage: string;
    username: AbstractControl;
    password: AbstractControl;
    rememberme: AbstractControl;

    form: FormGroup;


    constructor(private _fb: FormBuilder,
                private _router: Router,
                private _route: ActivatedRoute,
                private _loginService: LoginService) {
        this.form = this._fb.group({
            'username': ['', Validators.compose([Validators.required, Validators.minLength(4)])],
            'password': ['', Validators.compose([Validators.required, Validators.minLength(4)])],
            'rememberme': [true]
        });
        this.username = this.form.controls['username'];
        this.password = this.form.controls['password'];
        this.rememberme = this.form.controls['rememberme'];
        this.showError = this._route.data['showerror'];
    }

    ngOnInit() {
    }

    login() {
        const qm: SysUser = SysUser.create();
        qm.serName = this.username.value;
        qm.serPass = Md5.hashStr(this.password.value).toString();
        const self = this;
        this._loginService.login(qm, {
            success: (result) => {
                console.log('login --> %o', result);
                localStorage.setItem('loginToken', result.domain.loginToken);
                self._router.navigate(['/module']);
            },
            error: (result) => {
                this.showError = true;
                this.systemErrorMessage = result.statusText;
            }
        }).subscribe();
    }
}
